package com.xxx.springboot.util;


import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * AES加密/解密工具
 */
public class AESUtil {

	private static String SALT_KEY = "12345#wsxqwe@xxx"; 	// salt key
	private static String VECTOR_KEY = "abcdefxxx1234567"; 	// vector key
	private static String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";  // CBC/PKCS5Padding

	/**
	 * content: 加密内容
	 * vectorKey: 加密的向量，16位字符串
	 */
	public static String encrypt(String content) throws Exception {
		Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
		SecretKey secretKey = new SecretKeySpec(SALT_KEY.getBytes(), "AES");
		IvParameterSpec iv = new IvParameterSpec(VECTOR_KEY.getBytes());
		cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
		byte[] encrypted = cipher.doFinal(content.getBytes());
		return Base64.encodeBase64String(encrypted);
	}

	/**
	 * content: 解密内容(base64编码格式)
	 * slatKey: 加密时使用的盐，16位字符串
	 * vectorKey: 加密时使用的向量，16位字符串
	 */
	public static String decrypt(String base64Content) throws Exception {
		Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
		SecretKey secretKey = new SecretKeySpec(SALT_KEY.getBytes(), "AES");
		IvParameterSpec iv = new IvParameterSpec(VECTOR_KEY.getBytes());
		cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
		byte[] content = Base64.decodeBase64(base64Content);
		byte[] encrypted = cipher.doFinal(content);
		return new String(encrypted);
	}

	public static void main(String[] args) throws Exception {
		String message = "HPBL1ER21AG615XY";
		System.out.println("message: " + message);
		String encryptMsg = encrypt(message);
		System.out.println("encrypted: " + encryptMsg);

		String decryptedMsg = decrypt(encryptMsg);
		System.out.println("decrypted: " + decryptedMsg);
	}
}
